package com.hxy.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AuthenticationEntryPointHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");

        System.out.println(e.getMessage());
        System.out.println(e.getClass().getTypeName());

        PrintWriter writer = httpServletResponse.getWriter();
        // JSON,fastjson
        String s = new ObjectMapper().writeValueAsString("{\"code\":500,\"msg\":AuthenticationEntryPoint" + e.getMessage() + "}");
        writer.println(s);
        writer.flush();
        writer.close();
    }
}
